# !/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import os
import sys
import jinja2
from jinja2 import Environment
from util.code import render, parse, clear_out
import importlib


if __name__ == '__main__':
    if not os.path.isdir("out/"):
        os.mkdir("./out")
    clear_out()
    # 创建一个包加载器对象
    templateLoader = jinja2.FileSystemLoader(searchpath="templates")
    env = Environment(loader=templateLoader)
    config = 'model.json'
    if len(sys.argv) == 2:
        config = sys.argv[1]
    with open(config, 'r', encoding="utf-8") as f:
        s1 = json.load(f)
        schema = parse(s1)
        # print(schema)
        # 添加全局变量
        env.globals['package'] = schema.package
        env.globals['author'] = schema.author
        now = datetime.datetime.now()
        env.globals['systime'] = now.strftime("%Y-%m-%d %H:%M:%S")
        env.globals['date'] = now.strftime("%Y-%m-%d")
        env.globals['_{'] = '{'
        env.globals['_}'] = '}'
        # print(env.globals)
        templates = schema.templates
        tables = schema.tables
        for table in tables:
            if not table.enable:
                continue
            for tpl in templates:
                if not tpl.enable:
                    continue
                s = render(env, table, tpl, "out/")
                # print(s)
        for engine in schema.engines:
            module = importlib.import_module('engines.' + engine)
            init_schema = getattr(module, 'init_schema')
            init_schema(schema, env)
